import store from '../store/index.js'
import {
	REQUEST_URL
} from './config.js'
import whiteListPath from './whiteListPath.js'
// import headtoken from './headtoken.js'
import serverPath from './path.js'
const base = {
	upload: function(filePath) {
		let userToken = uni.getStorageSync("token")
		
		//开发固定token使用
		if (process.env.NODE_ENV === 'development') {
			userToken = 'ab18aff215c9feb64b5c3f66cfa59247'
		}
		return new Promise((solve, reject) => {
			uni.uploadFile({
				url: this.interfaceUrl() + serverPath.upload,
				filePath,
				header: {
					'token': userToken

				},
				name: 'image',
				success: (res) => {
					const {
						data
					} = JSON.parse(res.data)
					console.log(data)
					solve(data.img)
				},
				fail(res) {
					base.hideLoading()
				}
			})
		})
	},
	uploadMultipul: async function(fileList) {
		const uploadList = []
		const imgList = []
		for (let i = 0; i < fileList.length; i++) {
			const img = await this.upload(fileList[i])
			imgList.push(img)
		}
		return imgList

	},
	toast: function(text, duration, success) {
		uni.showToast({
			title: text,
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	toastBack: function(text, duration, success) {
		uni.showToast({
			title: text,
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
		setTimeout(function() {
			uni.navigateBack({})
		}, duration || 2000)
	},
	px: function(num) {
		return uni.upx2px(num) + 'px';
	},
	interfaceUrl: function() {
		if (process.env.NODE_ENV === 'development') {
			return REQUEST_URL
		} else if (process.env.NODE_ENV === 'production') {
			return REQUEST_URL
		}
	},
	showLoading(params) {
		if (!params) {
			params = {
				title: '加载中...',
				mask: true
			}
		}
		uni.showLoading(params)
	},
	hideLoading() {
		uni.hideLoading()
	},
	request: function(url, method, postData, LoadingText, type,tokenshow) {
		// const userToken = store.state.token
		let headtoken_show = 0;
		let userToken = uni.getStorageSync('token')
		// let userToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxNDEiLCJhdWQiOiIiLCJleHAiOjE2NDI3NjM5OTMsImlhdCI6MTY0Mjc2MzkzMywiaXNzIjoiIiwianRpIjoiMzQ5OGU0MTFjOTFiMzFjZTU1ZmQwMzlkMWI5MWVlYTIiLCJuYmYiOjE2NDI3NjM5MzMsInN1YiI6IiJ9.OZBBojIt0MmGeJFssSzAKiCB5uY3qCeOk0L-vkRusjo'
		let token_navlogin = tokenshow==false ? tokenshow : true 
		
		// console.log("token1:" + userToken)
		//开发固定token使用
		// if (process.env.NODE_ENV === 'development') {
		// 	userToken = 'ab18aff215c9feb64b5c3f66cfa59247'
		// }
		// console.log("token2:" + userToken)
		//是否需要head携带token
		// console.log('token_navlogintoken_navlogintoken_navlogin')
		// console.log(token_navlogin)
		// return
		if (whiteListPath.indexOf(url) != -1) {

		} else {
			headtoken_show = 1

		}

		// 如果不在白名单又需要token,就跳到登录页
		if (whiteListPath.indexOf(url) == -1 && userToken == '' && token_navlogin == true) {
			console.log('检查接口是否在白名单中！')
			return
		}

		//接口请求
		if (LoadingText) {
			this.showLoading({
				mask: true,
				title: LoadingText === true ? '加载中...' : LoadingText,
			})
		}
		return new Promise((resolve, reject) => {
			// postData.city_id = uni.getStorageSync('city_id')
			console.log('请求参数为：')
			console.log(postData)
			console.log('请求地址为',this.interfaceUrl() + url)
			uni.request({
				url: this.interfaceUrl() + url,
				data: postData,
				header: {
					'content-type': 'application/json',
					'token': headtoken_show == 0 ? '' : userToken,
					'Authorization':  'Bearer '+ userToken
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					LoadingText && this.hideLoading()
					if (res.statusCode !== 200) {
						this.toast('请求异常1' + res.errMsg)
						return
					}
					// if (res.data.code !== 200 && res.data.code !== 1 && res.data.code !==0) {
					// 	this.toast(res.data.message)
					// 	if (res.data.code === 401) {
					// 		store.commit('setToken', '');
					// 		store.commit('setUserInfo', '');
					// 		uni.navigateTo({
					// 			url: '/pages/login/login'
					// 		})
					// 		return
					// 	}
					// 	if (res.data.message == '用户未登录') {
					// 		console.log('1111')
					// 		uni.navigateTo({
					// 			url: '/pages/login/login',
					// 			complete(e) {
					// 				console.log(e)
					// 			}
					// 		})
					// 		return
					// 	}
					// 	// console.log('1111')
					// 	reject && reject(res)
					// } else {
						
					// 	resolve(res.data)
					// }
					resolve(res.data)
				},
				fail: (res) => {
					console.log('898989')
					if (res.errMsg)
						this.toast('请求异常2' + res.errMsg)
					else
						this.toast('请求异常2' + JSON.stringify(res))
					this.hideLoading()
					uni.stopPullDownRefresh();
					reject(res)
				}
			})
		})
	},

	requestCustom: function(url, method, postData, LoadingText, type) {

		//接口请求
		if (LoadingText) {
			this.showLoading({
				mask: true,
				title: LoadingText === true ? '加载中...' : LoadingText,
			})
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: url,
				data: postData,
				header: {
					'content-type': type ? 'application/x-www-form-urlencoded' :
						'application/json',
					'Authorization': 'APPCODE 11111111111111111111'
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					LoadingText && this.hideLoading()
					if (res.statusCode !== 200) {
						this.toast('请求异常')
						return
					}
					resolve(res.data)
				},
				fail: (res) => {
					this.toast('请求异常')
					this.hideLoading()
					uni.stopPullDownRefresh();
					reject(res)
				}
			})
		})
	},


	//保留小数
	keepDecimal(num, length = 2) {
		let nums = Number(num) || 0
		return nums.toFixed(length)
	},
	hideKeyBoard() {
		//旧版本有bug,先用这个兼容
		//#ifdef APP-PLUS
		plus.key.hideSoftKeybord();
		//#endif
		uni.hideKeyboard();
	},
	// 复制
	copyText(text) {
		// #ifdef APP-PLUS
		try {
			var os = plus.os.name;
			text = text || '';
			if ('iOS' == os) {
				var pasteboard = plus.ios.invoke('UIPasteboard', 'generalPasteboard');
				plus.ios.invoke(pasteboard, 'setValue:forPasteboardType:', text, 'public.utf8-plain-text');
			} else {
				var main = plus.android.runtimeMainActivity();
				var clip = main.getSystemService('clipboard');
				plus.android.invoke(clip, 'setText', text);
			}
			this.toast('复制成功')
		} catch (e) {
			console.error('error @setClipboardText!!');
		}
		// #endif

		// #ifdef H5
		if (typeof document.execCommand === 'function') {
			const input = document.createElement('input')
			input.readOnly = true
			input.value = text
			input.style.position = 'absolute'
			input.style.width = '100px'
			input.style.left = '-10000px'
			document.body.appendChild(input)
			input.select()
			input.setSelectionRange(0, input.value.length)
			document.execCommand('copy')
			document.body.removeChild(input)
			this.toast('复制成功')
		} else {
			throw new Error(`Unsupported Function: 'document.execCommand'.`)
		}

		// #endif
		// #ifndef APP-PLUS || H5
		uni.setClipboardData({
			data: text,
			success: function() {}
		});
		// #endif
	},
	phoneReg(phone) {
		let reg = /^1[0-9]{10}$/ig;
		return reg.test(phone)
	},
	formatPhoneStar(phone) {
		if (!phone) {
			return ''
		}
		return phone.substr(0, 3) + "****" + phone.substr(7);
	},
	cardCodeReg(code) {
		const codeReg =
			/(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0[1-9]|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/;
		return codeReg.test(code)
	}
}
export default base;
